package com.example.qu_tao.View;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.qu_tao.R;
import com.example.qu_tao.entity.Address;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class DizhiguanliActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int REQUEST_ADD_ADDRESS = 1;
    private static final int REQUEST_EDIT_ADDRESS = 2;
    private Button addAddressButton;
    private RecyclerView addressRecyclerView;
    private LinearLayout emptyStateView;
    private List<Address> addressList = new ArrayList<>();
    private AddressAdapter addressAdapter;
    private ImageView backButton;
    // 统一SharedPreferences名称
    private static final String PREFS_NAME = "AddressPrefs";
    private static final String ADDRESS_LIST_KEY = "addressList";
    // 广播接收器，接收地址更新通知
    private BroadcastReceiver addressReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("ACTION_ADDRESS_UPDATED".equals(intent.getAction())) {
                Log.d("DizhiguanliActivity", "Received address update broadcast");
                loadAddresses(); // 重新加载数据
            }
        }
    };
    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dizhiguanli);
        addAddressButton = findViewById(R.id.addAddressButton);
        addressRecyclerView = findViewById(R.id.addressRecyclerView);
        emptyStateView = findViewById(R.id.emptyStateView);
        backButton = findViewById(R.id.back_button);
        addAddressButton.setOnClickListener(this);
        backButton.setOnClickListener(this);
        // 初始化RecyclerView
        addressRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        addressAdapter = new AddressAdapter(addressList);
        addressRecyclerView.setAdapter(addressAdapter);
        // 注册广播接收器
        IntentFilter filter = new IntentFilter("ACTION_ADDRESS_UPDATED");
        registerReceiver(addressReceiver, filter);
        // 读取存储的地址数据
        loadAddresses();
        updateEmptyState();
    }
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.addAddressButton) {
            Intent intent = new Intent(this, AddShouhuodizhiActfivity.class);
            startActivityForResult(intent, REQUEST_ADD_ADDRESS);
        } else if (id == R.id.back_button) {
            finish();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ADD_ADDRESS && resultCode == RESULT_OK && data != null) {
            // 处理新增地址
            Address newAddress = data.getParcelableExtra("address");
            if (newAddress != null) {
                if (newAddress.isDefault()) {
                    // 若新增默认地址，取消其他地址的默认状态
                    for (Address addr : addressList) {
                        addr.setDefault(false);
                    }
                }
                addressList.add(newAddress);
                addressAdapter.notifyDataSetChanged();
                saveAddresses();
                updateEmptyState();
            }
        } else if (requestCode == REQUEST_EDIT_ADDRESS && resultCode == RESULT_OK && data != null) {
            if (data.getBooleanExtra("isDelete", false)) {
                // 处理删除地址
                Address addressToDelete = data.getParcelableExtra("address");
                if (addressToDelete != null) {
                    boolean removed = addressList.remove(addressToDelete);
                    if (removed) {
                        addressAdapter.notifyDataSetChanged();
                        saveAddresses();
                        updateEmptyState();
                        Log.d("DizhiguanliActivity", "Address removed: " + addressToDelete.getReceiver());
                    }
                }
            } else {
                // 处理编辑地址（通过hashCode查找并替换）
                Address editedAddress = data.getParcelableExtra("address");
                if (editedAddress != null) {
                    int index = findAddressIndexByHash(editedAddress.hashCode());
                    if (index != -1) {
                        // 替换列表中的地址对象
                        addressList.set(index, editedAddress);
                        // 同步默认地址状态
                        if (editedAddress.isDefault()) {
                            for (Address addr : addressList) {
                                if (!addr.equals(editedAddress)) {
                                    addr.setDefault(false);
                                }
                            }
                        }
                        addressAdapter.notifyDataSetChanged();
                        saveAddresses();
                        updateEmptyState();
                        Log.d("DizhiguanliActivity", "Address updated: " + editedAddress.getReceiver());
                    } else {
                        Log.w("DizhiguanliActivity", "Address not found in list, reloading data");
                        loadAddresses(); // 若未找到，重新加载数据
                    }
                }
            }
        }
    }
    // 通过hashCode查找地址索引
    private int findAddressIndexByHash(int hash) {
        for (int i = 0; i < addressList.size(); i++) {
            if (addressList.get(i).hashCode() == hash) {
                return i;
            }
        }
        return -1;
    }
    private void updateEmptyState() {
        if (addressList.isEmpty()) {
            emptyStateView.setVisibility(View.VISIBLE);
            addressRecyclerView.setVisibility(View.GONE);
        } else {
            emptyStateView.setVisibility(View.GONE);
            addressRecyclerView.setVisibility(View.VISIBLE);
        }
    }
    // 保存地址数据到SharedPreferences
    private void saveAddresses() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            Gson gson = new Gson();
            String json = gson.toJson(addressList);
            editor.putString(ADDRESS_LIST_KEY, json);
            editor.apply();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "保存地址失败", Toast.LENGTH_SHORT).show();
        }
    }
    // 从SharedPreferences读取地址数据
    private void loadAddresses() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            String json = prefs.getString(ADDRESS_LIST_KEY, null);
            if (json != null) {
                Gson gson = new Gson();
                Type type = new TypeToken<List<Address>>() {}.getType();
                List<Address> loadedAddresses = gson.fromJson(json, type);
                addressList.clear();
                addressList.addAll(loadedAddresses);
                // 确保只有一个默认地址
                syncDefaultAddress();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "读取地址失败", Toast.LENGTH_SHORT).show();
        }
        addressAdapter.notifyDataSetChanged();
        updateEmptyState();
    }
    // 同步默认地址状态（确保只有一个默认地址）
    private void syncDefaultAddress() {
        boolean defaultFound = false;
        for (Address addr : addressList) {
            if (addr.isDefault()) {
                if (defaultFound) {
                    addr.setDefault(false); // 取消重复的默认地址
                } else {
                    defaultFound = true;
                }
            }
        }
        // 若没有默认地址，将第一个地址设为默认（可选逻辑）
        if (!defaultFound && !addressList.isEmpty()) {
            addressList.get(0).setDefault(true);
        }
    }
    // 地址适配器
    private class AddressAdapter extends RecyclerView.Adapter<AddressAdapter.AddressViewHolder> {
        private List<Address> addressList;
        public AddressAdapter(List<Address> addressList) {
            this.addressList = addressList;
        }
        @Override
        public AddressViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.address_item, parent, false);
            return new AddressViewHolder(view);
        }
        @Override
        public void onBindViewHolder(AddressViewHolder holder, int position) {
            Address address = addressList.get(position);
            holder.receiver.setText(address.receiver);
            holder.phone.setText(address.phone);
            String fullAddress = address.region + " " + address.detailAddress;
            holder.address.setText(fullAddress);
            holder.defaultTag.setVisibility(address.isDefault ? View.VISIBLE : View.GONE);
            holder.editImage.setOnClickListener(v -> {
                Intent intent = new Intent(v.getContext(), BianjidizhiActivity.class);
                intent.putExtra("isEdit", true);
                intent.putExtra("address", address);
                startActivityForResult(intent, REQUEST_EDIT_ADDRESS);
            });
            Log.d("AdapterBind", "Position: " + position + ", Receiver: " + address.receiver +
                    ", isDefault: " + address.isDefault());
        }
        @Override
        public int getItemCount() {
            return addressList.size();
        }
        class AddressViewHolder extends RecyclerView.ViewHolder {
            TextView defaultTag;
            TextView receiver;
            TextView phone;
            TextView address;
            ImageView editImage;
            public AddressViewHolder(View itemView) {
                super(itemView);
                defaultTag = itemView.findViewById(R.id.tv_default);
                receiver = itemView.findViewById(R.id.tv_receiver);
                phone = itemView.findViewById(R.id.tv_phone);
                address = itemView.findViewById(R.id.tv_address);
                editImage = itemView.findViewById(R.id.iv_edit);
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播接收器
        unregisterReceiver(addressReceiver);
    }
}